package Service

import (
	"TCPServer/Interfaces"
	"fmt"
	"strconv"
)

type MsgHandler struct {
	APIs      map[uint16]Interfaces.IRouter
	taskQueue []chan Interfaces.IRequest
}

func NewMessageHandler() *MsgHandler {
	return &MsgHandler{
		APIs:      make(map[uint16]Interfaces.IRouter),
		taskQueue: make([]chan Interfaces.IRequest, 10),
	}
}

func (mh *MsgHandler) DoMsgHandler(request Interfaces.IRequest) {
	handler, ok := mh.APIs[request.GetMsgID()]
	if !ok {
		fmt.Println("api msgId = ", request.GetMsgID(), " is not FOUND!")
	}
	handler.PreHandle(request)
	handler.Handle(request)
	handler.PostHandle(request)
}

func (mh *MsgHandler) AddRouter(msgID uint16, router Interfaces.IRouter) {
	if _, ok := mh.APIs[msgID]; ok {
		panic("repeated api , msgId = " + strconv.Itoa(int(msgID)))
	}
	mh.APIs[msgID] = router
}

func (mh *MsgHandler) StartTaskQueue() {
	for i := 0; i < 10; i++ {
		mh.taskQueue[i] = make(chan Interfaces.IRequest, 100)
		go mh.StartOneTaskQueue(mh.taskQueue[i])
	}
}
func (mh *MsgHandler) StartOneTaskQueue(reqChan chan Interfaces.IRequest) {
	for {
		select {
		case req := <-reqChan:
			mh.DoMsgHandler(req)
		}
	}
}
func (mh *MsgHandler) SendMsgToTaskQueue(request Interfaces.IRequest) {
	workID := request.GetMsgID() % 10
	mh.taskQueue[workID] <- request
}
